package com.goodluck.goodluckim.sdk.service;

import com.goodluck.goodluckim.db.DBManager;
import com.goodluck.goodluckim.db.greendao.TeamMemberDao;
import com.goodluck.goodluckim.db.model.TeamMember;
import com.goodluck.goodluckim.sdk.constant.CacheConstant;
import com.robin.lazy.cache.CacheLoaderManager;

/**
 * 群管理类
 * Created by wyj on 2018/9/26.
 */

public class TeamService {

    public interface TeamInfoCallback<T> {
        void onSuccess(T t);

        void onError();
    }

    /**
     * 群缓存的key头部
     */
    private static final String TEAM_HEARD_KEY = "team_";
    private TeamMemberDao teamMemberDao;

    public TeamService() {
        teamMemberDao = DBManager.getInstance().getDaoSession().getTeamMemberDao();
    }

    public void addTeamMember(TeamMember teamMember) {
        teamMemberDao.insertOrReplace(teamMember);
    }

    public void deleteTeamMember(TeamMember teamMember) {
        teamMemberDao.delete(teamMember);
        CacheLoaderManager.getInstance().delete(getKey(TEAM_HEARD_KEY, teamMember.getGroupsId(), teamMember.getUserId()));
    }

    public void updateTeamMember(TeamMember teamMember) {
        teamMemberDao.update(teamMember);
        TeamMember oldMember = CacheLoaderManager.getInstance().loadSerializable(getKey(TEAM_HEARD_KEY, teamMember.getGroupsId(), teamMember.getUserId()));
        if (oldMember != null) {
            CacheLoaderManager.getInstance().saveSerializable(getKey(TEAM_HEARD_KEY, teamMember.getGroupsId(), teamMember.getUserId()), teamMember, CacheConstant.MaxLimitTime);
        }
    }

    /**
     * 获取群成员信息,采用三级缓存，先从缓存获取，再从数据库获取，然后从网络获取
     *
     * @param userId
     * @return
     */
    public void getTeamMember(long teamId, long userId, TeamInfoCallback teamInfoCallback) {
        TeamMember teamMember = CacheLoaderManager.getInstance().loadSerializable(getKey(TEAM_HEARD_KEY, teamId, userId));
        if (teamMember == null) {
            teamMember = teamMemberDao.queryBuilder().where(TeamMemberDao.Properties.UserId.eq(userId)).unique();
        }
        if (teamMember != null) {
            CacheLoaderManager.getInstance().saveSerializable(TEAM_HEARD_KEY + userId, teamMember, CacheConstant.MaxLimitTime);
            teamInfoCallback.onSuccess(teamMember);
        }
        //网络请求
    }

    private String getKey(String headerKey, long... keys) {
        StringBuffer key = new StringBuffer(headerKey);
        for (int i = 0; i < keys.length; i++) {
            key.append("_" + keys[i]);
        }
        return key.toString();
    }
}
